package com.zhenghaijin.favoritesservice.service.impl;

import com.zhenghaijin.favoritesservice.mapper.FavoriteMapper;
import com.zhenghaijin.favoritesservice.model.Favorite;
import com.zhenghaijin.favoritesservice.service.FavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class FavoriteServiceImpl implements FavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public List<Favorite> getFavoritesByUserId(Long userId) {
        return favoriteMapper.findByUserId(userId);
    }

    @Override
    public boolean isFavorite(Long userId, Long animeId) {
        return favoriteMapper.findByUserIdAndAnimeId(userId, animeId) != null;
    }

    @Override
    public boolean addFavorite(Favorite favorite) {
        log.info("尝试添加收藏: 用户ID {}, 动漫ID {} - Attempting to add favorite for user: {}, anime: {}", favorite.getUserId(), favorite.getAnimeId(), favorite.getUserId(), favorite.getAnimeId());
        favorite.setCreatedAt(LocalDateTime.now());
        boolean success = favoriteMapper.insert(favorite) > 0;
        if (success) {
            log.info("成功添加收藏: 用户ID {}, 动漫ID {} - Successfully added favorite for user: {}, anime: {}", favorite.getUserId(), favorite.getAnimeId(), favorite.getUserId(), favorite.getAnimeId());
        } else {
            log.warn("添加收藏失败: 用户ID {}, 动漫ID {} - Failed to add favorite for user: {}, anime: {}", favorite.getUserId(), favorite.getAnimeId(), favorite.getUserId(), favorite.getAnimeId());
        }
        return success;
    }

    @Override
    public boolean removeFavorite(Long userId, Long animeId) {
        log.info("尝试移除收藏: 用户ID {}, 动漫ID {} - Attempting to remove favorite for user: {}, anime: {}", userId, animeId, userId, animeId);
        boolean success = favoriteMapper.deleteByUserIdAndAnimeId(userId, animeId) > 0;
        if (success) {
            log.info("成功移除收藏: 用户ID {}, 动漫ID {} - Successfully removed favorite for user: {}, anime: {}", userId, animeId, userId, animeId);
        } else {
            log.warn("移除收藏失败: 用户ID {}, 动漫ID {} - Failed to remove favorite for user: {}, anime: {}", userId, animeId, userId, animeId);
        }
        return success;
    }
}
